import axios from 'axios'
import { ElNotification } from 'element-plus'
import "element-plus/es/components/notification/style/css"

import $router from '../router/index'
//1.实例化axios对象
var service = axios.create({
    timeout: 10 * 100,
    baseURL: ''
})

// 2.设置请求拦截对象

service.interceptors.request.use(
    (config) => {
        config.headers['Authorization'] ='Bearer' + ' ' + localStorage.getItem('token')
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

//3.设置响应拦截对象

service.interceptors.response.use(
    (res) => {
        return res
    },
    (error) => {
        if (error.response.status == 401) {
            //弹框
            ElNotification({
                title: '提示',
                message: '登陆过期,请重新登录!',
                type: 'warning',
            })
            //删除token
            localStorage.removeItem('token')
            //重定向到登录页
            $router.push('/login')
        }
        else if (error.response.status == 404) {
            ElNotification({
                title: '提示',
                message: '访问路径有误!',
                type: 'warning',
            })
        }
        else if(error.response.status==500){
            ElNotification({
                title: '提示',
                message: '服务器内部错误!',
                type: 'warning',
            })
        }
        return Promise.reject(error)
    }
)

export default service